{% extends 'base.html'%}
{% load staticfiles %}
{%load i18n%}
{%block title%}{%trans 'Server list' %}{%endblock%}
{% block css %}
<link rel="stylesheet" href="{% static 'plugins/bootstrap-select/css/bootstrap-select.css' %} ">
<link rel="stylesheet" href="{% static 'plugins/json-forms/css/brutusin-json-forms.css' %} ">
<!-- DataTables css -->
<link rel="stylesheet" href="{% static "plugins/datatables/dataTables.bootstrap.css" %}">
<link rel="stylesheet" href="{% static "plugins/json-view/jquery.jsonview.min.css" %}">
{% endblock %}
{% block content %}
<section class="content">
    <div class="row">
        <div class="col-md-12">
            <!-- BEGIN EXAMPLE TABLE PORTLET-->
            <div class="box box-success">
                <div class="box-header with-border">
                    <div class="caption">
                        <button class="btn btn-primary" onclick="window.location.href = '{% url 'servercreate' %}'">
                            {%trans 'Add New' %}
                            <i class="fa fa-plus"></i>
                        </button>
                    </div>

                    <div class="box-tools pull-right">
                        <button type="button" class="btn btn-box-tool" data-widget="collapse"><i
                                class="fa fa-minus"></i>
                        </button>
                        <div class="btn-group">
                            <button type="button" class="btn btn-box-tool dropdown-toggle" data-toggle="dropdown">
                                <i class="fa fa-wrench"></i></button>
                            <ul class="dropdown-menu" role="menu">
                                <li><a href="#">{%trans 'Action' %}</a></li>
                                <li><a href="#">{%trans 'Another action' %}</a></li>
                                <li><a href="#">{%trans 'Something else here' %}</a></li>
                                <li class="divider"></li>
                                <li><a href="#">{%trans 'Separated link' %}</a></li>
                            </ul>
                        </div>
                        <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i>
                        </button>
                    </div>
                </div>
                <div class="box-body">
                    <table id="server_list" class="table table-hover table-striped">
                        <thead>
                        <tr>
                            <th>{%trans 'server name' %}</th>
                            <th>{%trans 'host name' %}</th>
                            <th>{%trans 'ip' %}</th>
                            <th>{%trans 'action' %}</th>
                            <th>{%trans 'connect' %}</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for element in object_list %}
                        <tr>
                            <td data-toggle="collapse" data-target="#expand{{element.id}}">{{ element.name }}</td>
                            <td data-toggle="collapse" data-target="#expand{{element.id}}">{{ element.hostname }}</td>
                            <td data-toggle="collapse" data-target="#expand{{element.id}}">{{ element.ip }}</td>
                            <td data-editable="false" class="text-center pull-left">
                                {% if perms.common.can_view_serverinfo %}<a class="btn btn-xs btn-primary" onclick="detail({{element.id}})">{%trans 'detail'%}</a>{% endif %}
                                {% if perms.common.can_change_serverinfo %}<a class="btn btn-xs btn-info" onclick="edit({{element.id}})">{%trans 'edit' %}</a>{% endif %}
                                {% if perms.common.can_delete_serverinfo %}<a class="btn btn-xs btn-danger" onclick="del({{element.id}},'{{element.name}}')">{%trans 'delete' %}</a>{% endif %}
                            </td>
                            <td>
                                <button class="btn btn-default" type="button" data-toggle="collapse" data-target="#expand{{element.id}}">
                                    {%trans 'connect'%}
                            </button>
                            </td>
                        </tr>
                        <tr id="expand{{element.id}}" class="collapse" aria-expanded="false" style="height: 0px;">
                            <td colspan="{{element.id}}">
                                <ul class="list-inline">
                                    {% ifequal element.credential.protocol 'ssh-password'%}
                                    {% if perms.common.can_connect_serverinfo %}
                                    <li><span><a><img src="{% static "images/securecrt.gif" %}" width="60px" onclick="connectwebterminalhelper({{element.id}},'ssh')"></a></span><p class="text-center">ssh</p></li>
                                    <li><span><a><img src="{% static "images/filezilla.gif" %}" width="60px" onclick="connectwebterminalhelper({{element.id}},'sftp')"></a></span><p class="text-center">sftp</p></li>
                                    <!--<li><span><a href="#"><img src="{% static "images/xmanager.gif" %}" width="60px"></a></span><p class="text-center">X11</p></li>-->
                                    <li><span><a href="{% url 'sshconnect' element.ip  element.id%}" target="_blank"><img src="{% static "images/terminal.gif" %}" width="60px"></a></span><p class="text-center">webssh</p></li>
                                    {% endif %}
                                    {% endifequal %}
                                    {% ifequal element.credential.protocol 'ssh-key'%}
                                    {% if perms.common.can_connect_serverinfo %}
                                    <li><span><a><img src="{% static "images/securecrt.gif" %}" width="60px" onclick="connectwebterminalhelper({{element.id}},'ssh')"></a></span><p class="text-center">ssh</p></li>
                                    <li><span><a><img src="{% static "images/filezilla.gif" %}" width="60px" onclick="connectwebterminalhelper({{element.id}},'sftp')"></a></span><p class="text-center">sftp</p></li>
                                    <!--<li><span><a href="#"><img src="{% static "images/xmanager.gif" %}" width="60px"></a></span><p class="text-center">X11</p></li>-->
                                    <li><span><a href="{% url 'sshconnect' element.ip  element.id%}" target="_blank"><img src="{% static "images/terminal.gif" %}" width="60px"></a></span><p class="text-center">webssh</p></li>
                                    {% endif %}
                                    {% endifequal %}
                                    {% ifequal element.credential.protocol 'ssh-key-with-password'%}
                                    {% if perms.common.can_connect_serverinfo %}
                                    <li><span><a><img src="{% static "images/securecrt.gif" %}" width="60px" onclick="connectwebterminalhelper({{element.id}},'ssh')"></a></span><p class="text-center">ssh</p></li>
                                    <li><span><a><img src="{% static "images/filezilla.gif" %}" width="60px" onclick="connectwebterminalhelper({{element.id}},'sftp')"></a></span><p class="text-center">sftp</p></li>
                                    <!--<li><span><a><img src="{% static "images/xmanager.gif" %}" width="60px"></a></span><p class="text-center">X11</p></li>-->
                                    <li><span><a href="{% url 'sshconnect' element.ip  element.id%}" target="_blank"><img src="{% static "images/terminal.gif" %}" width="60px"></a></span><p class="text-center">webssh</p></li>
                                    {% endif %}
                                    {% endifequal %}
                                    {% ifequal element.credential.protocol 'telnet'%}
                                    {% if perms.common.can_connect_serverinfo %}
                                    <!--<li><span><a><img src="{% static "images/securecrt.gif" %}" width="60px" onclick="connecttosshserver({{element.id}})"></a></span><p class="text-center">ssh</p></li>-->
                                    <li><span><a href="{% url 'guacamole' element.id%}" target="_blank"><img src="{% static "images/terminal.gif" %}" width="60px"></a></span><p class="text-center">webtelnet</p></li>
                                    {% endif %}
                                    {% endifequal %}
                                    {% ifequal element.credential.protocol 'vnc'%}
                                    {% if perms.common.can_connect_serverinfo %}
                                    <li><span><a><img src="{% static "images/vnc.gif" %}" width="60px" onclick="connectwebterminalhelper({{element.id}},'vnc')"></a></span><p class="text-center">vnc</p></li>
                                    <li><span><a href="{% url 'guacamole' element.id%}" target="_blank"><img src="{% static "images/webvnc.gif" %}" width="60px"></a></span><p class="text-center">webvnc</p></li>
                                    {% endif %}
                                    {% endifequal %}
                                    {% ifequal element.credential.protocol 'rdp'%}
                                    {% if perms.common.can_connect_serverinfo %}
                                    <li><span><a><img src="{% static "images/mstsc.gif" %}" width="60px" onclick="connectwebterminalhelper({{element.id}},'rdp')"></a></span><p class="text-center">rdp</p></li>
                                    <li><span><a href="{% url 'guacamole' element.id%}" target="_blank"><img src="{% static "images/webrdp.gif" %}" width="60px"></a></span><p class="text-center">webrdp</p></li>
                                    {% endif %}
                                    {% endifequal %}
                                </ul>
                            </td>
                        </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
            <!-- END EXAMPLE TABLE PORTLET-->
        </div>

    </div>
</section>
{% endblock %}
{% block js %}
<script src="{% static 'plugins/markdown/markdown.js' %} "></script>
<script src="{% static 'plugins/bootstrap-select/js/bootstrap-select.js' %} "></script>
<script src="{% static 'plugins/bootstrap-select/js/i18n/defaults-en_US.js' %} "></script>
<script src="{% static 'plugins/json-forms/js/brutusin-json-forms.js' %} "></script>
<script src="{% static 'plugins/json-forms/js//brutusin-json-forms-bootstrap.js' %} "></script>
<!-- DataTables -->
<script src="{% static "plugins/datatables/jquery.dataTables.js" %}"></script>
<script src="{% static "plugins/datatables/dataTables.bootstrap.js" %}"></script>
<script src="{% static "plugins/json-view/jquery.jsonview.min.js" %}"></script>
<script src="{% static "plugins/bootbox/bootbox.js" %}"></script>
<!--<script type="application/javascript">-->
    <!--$(function () {-->
        <!--$('#server_list').DataTable({-->
            <!--"paging": true,-->
            <!--"lengthChange": false,-->
            <!--"searching": true,-->
            <!--"ordering": true,-->
            <!--"info": true,-->
            <!--"iDisplayLength": 50,-->
            <!--"autoWidth": false,-->
            <!--"aoColumns":[-->
                <!--null,-->
                <!--null,-->
                <!--null,-->
                <!--null,-->
                <!--null,-->
                <!--null-->
            <!--]-->
        <!--});-->
    <!--});-->
<!--</script>-->
<script type="application/javascript">
    function detail(id) {
        var dialog = bootbox.dialog({
            title: '{%trans 'Server information detail' %}',
            message: '<p><i class="fa fa-spin fa-spinner"></i> {%trans 'Loading...' %}</p>'
        });
        dialog.init(function(){
            var url = '{% url 'serverinfor-list' %}';
            $.ajax({
                url: url + id +'/',
                type: 'GET',
                success: function(data, textStatus, jqXHR) {
                    var schema = {
                        "type": "object",
                        "properties": {
                            "name": {
                                "type": "string",
                                'title': "{%trans 'credential name' %}",
                                "description": "{%trans 'credential name' %}",
                                "required": true,
                                "minLength": 1,
                                "maxLength": 40,
                                "readOnly": true,
                            },
                            "hostname": {
                                "type": "string",
                                'title': "{%trans 'hostname' %}",
                                "description": "{%trans 'server hostname' %}",
                                "required": true,
                                "minLength": 1,
                                "maxLength": 40,
                                "readOnly": true,
                            },
                            "ip": {
                                "type": "string",
                                'title': "{%trans 'ip' %}",
                                "description": "{%trans 'ip' %}",
                                "required": true,
                                "format": "ipv4",
                                "readOnly": true,
                            },
                            "credential": {
                                "type": "string",
                                'title': "{%trans 'credential' %}",
                                "description": "{%trans 'credential' %}",
                                "enum":[
                                {% for credential in credentials %}
                                    "{{ credential.name }}",
                                {% endfor %}
                                 ],
                                "readOnly": true,
                                "required": true,
                            },
                        }
                     };
                    dialog.find('.bootbox-body').html("<div id='container'></div>");
                    var BrutusinForms = brutusin["json-forms"];
                    var bf = BrutusinForms.create(schema);
                    var container = document.getElementById('container');
                    $("#container").append('<p><i class="fa fa-spin fa-spinner"></i> {% trans 'Loading...' %}</p>');
                    $.ajax({url: data['credential'], success: function(result){
                        data['credential'] = result['name'];
                        delete data['onlinedatetime'];
                        delete data['url'];
                        delete data['updatedatetime'];
                    }}).done(function () {
                        setTimeout(function () {
                            $("#container").empty();
                            bf.render(container, data);
                        },2000);
                    });



                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $.each(JSON.parse(XMLHttpRequest.responseText), function(key, value){
                        $.each(value, function(index, value) {
                            toastr["error"]("{%trans 'Please check field' %} "+key + " {%trans 'error' %}: "+ value);
                        });
                    });
                }
            });
        });
    }
    function edit(id) {
        var dialog = bootbox.confirm({
            title: '{%trans 'Server information edit' %}',
            message: '<p><i class="fa fa-spin fa-spinner"></i> {%trans 'Loading...' %}</p>',
            buttons: {
                confirm: {
                    label: '{%trans 'submit' %}',
                    className: 'btn-danger'
                },
                cancel: {
                    label: '{%trans 'cancel' %}',
                    className: 'btn-success'
                }
            },
            callback: function (result) {
                if (result){
                    if ($.gbf.validate()) {
                        var jsondata = $.gbf.getData();

                        //Replace credential to url
                        var credentialproperity = {
                            {% for credential in credentials %}
                                 "{{ credential.name }}":{{credential.id}},
                            {% endfor %}
                        };
                        var url = "{% url 'credential-list' %}";
                        jsondata['credential'] = "http://"+window.location.host + url + credentialproperity[jsondata['credential']] + "/";

                        //console.log(jsondata);
                        $.ajax({
                            type: "PUT",
                            url: '{% url 'serverinfor-list' %}' + id + '/',
                            data: JSON.stringify(jsondata, null, 4),
                            dataType: "json",
                            contentType: "application/json; charset=utf-8",
                            success: function (data) {
                                toastr["success"]("Update server info " +data.name + " success!");
                                setTimeout(function () {
                                    location.reload();
                                },2000);
                            },
                            failure: function (errMsg) {
                                toastr["error"](errMsg);
                            },
                            error: function(XMLHttpRequest, textStatus, errorThrown) {
                                $.each(JSON.parse(XMLHttpRequest.responseText), function(key, value){
                                    $.each(value, function(index, value) {
                                        toastr["error"]("Please check field "+key + " error: "+ value);
                                    });
                                });
                            }
                        });
                    }
                }
            }
        });
        dialog.init(function(){

            $.ajax({
                url: '{% url 'serverinfor-list' %}' + id + '/',
                type: 'GET',
                success: function(data, textStatus, jqXHR) {
                    var schema = {
                        "type": "object",
                        "properties": {
                            "name": {
                                "type": "string",
                                'title': "{%trans 'credential name' %}",
                                "description": "{%trans 'credential name' %}",
                                "required": true,
                                "minLength": 1,
                                "maxLength": 40,
                            },
                            "hostname": {
                                "type": "string",
                                'title': "{%trans 'hostname' %}",
                                "description": "{%trans 'server hostname' %}",
                                "required": true,
                                "minLength": 1,
                                "maxLength": 40,
                            },
                            "ip": {
                                "type": "string",
                                'title': "{%trans 'ip' %}",
                                "description": "{%trans 'ip' %}",
                                "required": true,
                                "format": "ipv4",
                            },
                            "credential": {
                                "type": "string",
                                'title': "{%trans 'credential' %}",
                                "description": "{%trans 'credential' %}",
                                "required": true,
                                "enum":[
                                {% for credential in credentials %}
                                    "{{ credential.name }}",
                                {% endfor %}
                                ]
                        },
                    }
                    };
                    $.ajax({url: data['credential'], success: function(result){
                        data['credential'] = result['name'];
                    }});
                    dialog.find('.bootbox-body').html("<div id='container'></div>");
                    var BrutusinForms = brutusin["json-forms"];
                    var bf = BrutusinForms.create(schema);
                    var container = document.getElementById('container');

                    $("#container").append('<p><i class="fa fa-spin fa-spinner"></i> {%trans 'Loading...' %}</p>');
                    setTimeout(function () {
                        $("#container").empty();
                        bf.render(container, data);
                    },2000);

                    $.gbf = bf;
                },
                error: function(data, textStatus, jqXHR) {
                    toastr['error'](data);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $.each(JSON.parse(XMLHttpRequest.responseText), function(key, value){
                        $.each(value, function(index, value) {
                            toastr["error"]("{%trans 'Please check field' %} "+key + " {%trans 'error' %}: "+ value);
                        });
                    });
                }
            });
        });
    };
    function del(id,name) {
        var dialog = bootbox.confirm({
            title: "<a class='text-danger'>"+'{%trans 'delete server' %} ' + name +"</a>",
            message: '{%trans 'Are you sure to delete server' %} ' + name +' ?',
            buttons: {
                confirm: {
                    label: '{%trans 'delete' %}',
                    className: 'btn-danger'
                },
                cancel: {
                    label: '{%trans 'cancel' %}',
                    className: 'btn-success'
                }
            },
            callback: function (result) {
                if (result){
                    $.ajax({
                        type: "DELETE",
                        url: '{% url 'serverinfor-list' %}' + id + '/',
                        dataType: "json",
                        success: function (data) {
                                toastr["success"]("{%trans 'Delete server' %} " +name +" {%trans 'success' %}!");
                                setTimeout(function () {
                                    location.reload();
                                },2000);

                        },
                        failure: function (errMsg) {
                            toastr["error"](errMsg);
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                            $.each(JSON.parse(XMLHttpRequest.responseText), function(key, value){
                                $.each(value, function(index, value) {
                                    toastr["error"]("{%trans 'Please check field' %} "+key + " {%trans 'error' %}: "+ value);
                                });
                            });
                        }
                    });
                }
            }
        });
    }
    function connectwebterminalhelper(serverid,protocol){
        $.ajax({
         type: "POST",
         url: "{% url 'dynamicpassword' %}",
         data: {"serverid":serverid,"protocol":protocol},
         dataType: "json",
         success: function (data) {
                if (data.status){
                    var server_address = window.location.hostname;
                    var user_pass_dict = data.message;
                    if (protocol == 'ssh' || protocol == 'sftp'){
                        var server_remote_port = 2100;
                    }else{
                        var server_remote_port = 3389;
                    }
                    var username = user_pass_dict.username;
                    var temp_pass = user_pass_dict.password;
                    var protocol_path = "wssh://"+ protocol +"#"+server_address+"#"+server_remote_port+"#"+username+"#"+temp_pass;
                    window.location.href = protocol_path
                }
         },
         failure: function (errMsg) {
             toastr["error"](errMsg);
         }
     });
    }
</script>
{% endblock %}